package com.itheima.wms.interceptor;

import cn.hutool.core.util.StrUtil;
import com.itheima.wms.controller.vo.UserInfoVo;
import com.itheima.wms.utils.JwtUtil;
import com.itheima.wms.utils.UserThreadLocalUtil;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Slf4j
@Component
public class LoginIntercaptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String threadName = Thread.currentThread().getName();
        log.info("LoginInterceptor 当前线程名称:{}", threadName);

        //1. 获取请求中的token
        String token = request.getHeader("Authorization");
        //2. 判断token令牌是否存在
        if (StrUtil.isEmpty(token)) {
            //2.1 不存在 校验失败 返回 401
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //2.2 存在 校验token
        Map<String, Object> claims = JwtUtil.parseJwt(token);
        //3. 解析token , 获取解析结果
        if (claims == null) {
            //3.1 解析失败 校验失败返回401
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //保存数据到当前线程
        int userId = Integer.parseInt(claims.get("id").toString());
        String name = claims.get("name").toString();

        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setId(userId);
        userInfoVo.setName(name);
        UserThreadLocalUtil.set(userInfoVo);

        //3.2 解析成功 , 校验通过, 直接放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理线程中的数据防止内存泄漏
        UserThreadLocalUtil.remove();
    }
}
